import { defineStore } from "pinia";
import { reactive } from "vue";
import Cookies from "js-cookie";
import Cache from "@/common/utils/cache";
import to from "await-to-js";
import { $logout, $getInfo } from "@/apis/user/user";
import { useStore as useTagsStore } from "@/store/tags";
interface infoInterface {
  token: string,
  id: string,
  name: string,
  avatar: string,
  roles: string[],
  permissions: string[],
}
interface loginInfoInterface {
  token: string,
}
export const useStore = defineStore('user', () => {
  const info = reactive({
    token: '',
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  } as infoInterface)
  // 登录
  const login = async (loginInfo: loginInfoInterface) => {
    info.token = loginInfo.token || '';
  }

  const SET_ROLES = (roles) => {
    info.roles = roles;
  }

  const SET_PERMISSIONS = (permissions) => {
    info.permissions = permissions;
  }

  const SET_ID = (id) => {
    info.id = id;
  }
  const SET_NAME = (name) => {
    info.name = name;
  }
  const SET_AVATAR = (avatar) => {
    info.avatar = avatar;
  }

  // 获取用户信息
  const GetInfo = async () => {
    const [err, res]: any = await to($getInfo());
    if (!err) {
      const user = res.data?.user;
      const avatar = (user.avatar == "" || user.avatar == null) ? null : process.env.VUE_APP_BASE_API + user.avatar;
      if (res.data?.roles && res.data?.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        SET_ROLES(res?.data?.roles);
        SET_PERMISSIONS(res?.data?.permissions);
      } else {
        SET_ROLES(['ROLE_DEFAULT']);
      }
      SET_ID(user.userId);
      SET_NAME(user.userName);
      SET_AVATAR(avatar);
    }
    return [err, res];
  }
  // 登出
  const logout = async () => {
    const tagsStore = useTagsStore();
    await $logout();
    info.token = '';
    info.roles = [];
    info.permissions = [];
    tagsStore.init();
  }
  return {
    info,
    login,
    logout,
    GetInfo,
  }
}, {
  persist: {
    enabled: true,
    key: new Cache().defineKey('user'),
    pick: ['info.token'],
    storage: {
      getItem: (key: string) => Cookies.get(key),
      setItem: (key: string, val: any) => Cookies.set(key, val),
      removeItem: (key: string) => Cookies.remove(key),
    },
  }
} as any)